Help needed with split and sort 您所在的位置:网站首页 python list数组split Help needed with split and sort

Help needed with split and sort

#Help needed with split and sort| 来源: 网络整理| 查看: 265

It has been mentioned that the .lower() or .upper() is to normlise the words so that eg “AGE” and “age” sort together because the default sort compares the strings directly, and strings compare by the rodinal values of their letters, and the entire UPPERCASE range occurs before the lowercase range.

But you can wort using the original words:

words = my_str.split() sorted_words = sorted(words, key=str.lower) print(sorted_words)

The sorted() and list.sort() functions accept an optional key= parameter which is a function to compute the key for the sort comparison. See its documentation:

Python documentation Built-in Functions

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...

Without the key= parameter, the comparison key is the value itself.

With the parameter, the key function is called on each value to get what to compare. In the example above we’re using str’s .lower function, so that the sort compares the lowercase forms of the words. The words themselves are unchanged.

As another example, when two words differ only in case we often (in English) for the uppercase one before the lowercase one eg in document indices etc. You could invoke the sort like this:

sorted_words = sorted( words, key=lambda word: (word.lower(), word), )

Here we’re doing something more sophisticated for the sort comparison key: we’re computing a 2-tuple of the lowercase form of the word, and its original, eg:

('age', 'Age')

When you compare tuples (or any sequence, the comparison compares the first member, then if they’re the same then the second member and so forth. In this way, if the lowercase forms are different, that controls the sort. But if they’re the same eg 'Age' and 'age', their lower case forms will be the same, and we fall back to their original forms, which would sort 'Age' before 'age'.

The lambda in the example is Python syntax for an anonymous function. In this case is accepts one argument (word) and returns the 2-tuple.

We could write the example like this:

def word_sort_key(word): return (word.lower(), word) sorted_words = sorted(words, key=word_sort_key)

which works exactly the same, but for small things like this it is common to write a lambda directly in the call.

Cheers, Cameron Simpson [email protected]



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有